import { defineStore } from 'pinia';
import axios from 'axios';

// 尝试从localStorage获取保存的城市信息
let savedCity = '北京'; // 默认值为北京

try {
  const savedWeatherData = localStorage.getItem('weatherData');
  if (savedWeatherData) {
    const parsedData = JSON.parse(savedWeatherData);
    if (parsedData.location && parsedData.location.city) {
      savedCity = parsedData.location.city;
    }
  }
} catch (e) {
  console.error('Failed to load saved weather data:', e);
}

// 直接使用天气API

// 创建一个专门用于天气API的axios实例，完全独立于项目配置
const weatherAxios = axios.create({
  timeout: 10000, // 设置超时时间为10秒
  headers: {
    'Content-Type': 'application/json'
  },
  // 明确不设置baseURL，确保请求直接发送
  baseURL: ''
});

export const useWeatherStore = defineStore('weather', {
  state: () => ({
    currentWeather: null,
    forecast: [],
    // 确保location对象始终存在且city有默认值
    location: {
      city: savedCity, // 使用从localStorage恢复的城市或默认城市
    },
    loading: false,
    error: null,
    lastUpdated: null
  }),

  getters: {
    // 获取天气图标
    weatherIcon: (state) => {
      if (!state.currentWeather) return '';
      
      const iconMap = {
        '晴': '☀️',
        '多云': '⛅',
        '阴': '☁️',
        '小雨': '🌦️',
        '中雨': '🌧️',
        '大雨': '⛈️',
        '雷阵雨': '⛈️',
        '雪': '❄️',
        '雾': '🌫️'
      };
      
      return iconMap[state.currentWeather.type] || '🌤️';
    },
    
    // 获取温度范围
    temperatureRange: (state) => {
      if (!state.forecast || state.forecast.length === 0) return '';
      
      const today = state.forecast[0];
      return `${today.low}°C ~ ${today.high}°C`;
    },
    
    // 获取适合的衣物建议
    clothingSuggestion: (state) => {
      if (!state.currentWeather) return '';
      
      const temp = parseInt(state.currentWeather.temperature.replace('°C', ''));
      const weatherType = state.currentWeather.type;
      
      if (temp < 5) {
        return '天气寒冷，建议穿着羽绒服、厚毛衣等保暖衣物';
      } else if (temp < 15) {
        return '天气较凉，建议穿着外套、毛衣等';
      } else if (temp < 25) {
        return '天气舒适，建议穿着长袖衬衫、薄外套等';
      } else {
        return '天气炎热，建议穿着短袖、短裤等清凉衣物';
      }
    }
  },

  actions: {
    // 获取天气数据
    async fetchWeatherData(cityName = null) {
      try {
        this.loading = true;
        this.error = null;
        
        // 确保location对象存在
        if (!this.location) {
          this.location = { city: '北京' };
        }
        
        let targetCity = '北京'; // 默认值
        
        // 优先级: 传入的城市名 > 当前location.city > 默认值
        if (typeof cityName === 'string' && cityName.trim()) {
          targetCity = cityName.trim();
        } else if (cityName !== null && typeof cityName === 'object' && cityName.city) {
          targetCity = cityName.city;
        } else if (this.location.city) {
          targetCity = this.location.city;
        }
        
        // 更新location，确保始终有值
        this.location.city = targetCity;
        
        // 使用专门的axios实例发送天气API请求
        const response = await weatherAxios.get('https://api.seniverse.com/v3/weather/daily.json', {
          params: {
            key: 'Sw5zhiqXUwBwlJMyn',
            location: targetCity,
            language: 'zh-Hans',
            unit: 'c'
          },
          timeout: 10000 // 设置超时时间为10秒
        });
        
        if (response.data && response.data.results && response.data.results.length > 0) {
          const data = response.data.results[0];
          
          // 设置当前天气
          const today = data.daily[0];
          this.currentWeather = {
            type: today.text_day,
            temperature: `${today.high}°C`,
            humidity: `${today.humidity}%`,
            wind: `${today.wind_direction}${today.wind_scale}级`,
            aqi: null // 和风天气API没有直接提供AQI数据
          };
          
          // 设置天气预报（只有三天的数据）
          this.forecast = data.daily.map(day => ({
            date: day.date,
            type: day.text_day,
            high: day.high,
            low: day.low,
            fengxiang: day.wind_direction,
            fengli: `${day.wind_scale}级`
          }));
          
          // 更新最后更新时间
          this.lastUpdated = new Date();
          
          // 缓存天气数据
          localStorage.setItem('weatherData', JSON.stringify({
            currentWeather: this.currentWeather,
            forecast: this.forecast,
            location: this.location,
            lastUpdated: this.lastUpdated
          }));
          
          return data;
        } else {
          throw new Error('获取天气数据失败: 返回数据格式不正确');
        }
      } catch (error) {
        
        // 尝试从本地缓存获取数据
        try {
          const cachedWeather = localStorage.getItem('weatherData');
          if (cachedWeather) {
            const parsedData = JSON.parse(cachedWeather);
            // 安全地更新状态，确保每个属性都存在
            if (parsedData.currentWeather) {
              this.currentWeather = parsedData.currentWeather;
            }
            if (Array.isArray(parsedData.forecast)) {
              this.forecast = parsedData.forecast;
            }
            // 添加对location对象的存在性检查，避免出现null访问错误
            if (parsedData.location && typeof parsedData.location === 'object') {
              // 确保缓存的location对象包含city属性
              if (parsedData.location.city) {
                // 保留city属性
                this.location.city = parsedData.location.city;
              } else {
                this.location.city = '北京'; // 使用默认城市
              }
            } else {
              // 确保location.city有值
              this.location.city = this.location.city || '北京';
            }
            if (parsedData.lastUpdated) {
              this.lastUpdated = parsedData.lastUpdated;
            }
          } else {
            // 如果没有缓存数据，设置一些模拟数据以避免页面空白
            console.warn('没有找到缓存的天气数据，使用模拟数据');
            this.currentWeather = {
              type: '晴',
              temperature: '25°C',
              humidity: '50%',
              wind: '南风3级',
              aqi: null
            };
            this.forecast = [
              { date: new Date().toISOString().split('T')[0], type: '晴', high: 25, low: 18, fengxiang: '南风', fengli: '3级' },
              { date: new Date(Date.now() + 86400000).toISOString().split('T')[0], type: '多云', high: 23, low: 17, fengxiang: '北风', fengli: '2级' },
              { date: new Date(Date.now() + 172800000).toISOString().split('T')[0], type: '阴', high: 22, low: 16, fengxiang: '东北风', fengli: '3级' }
            ];
          }
        } catch (e) {
          console.error('解析缓存的天气数据失败:', e);
          // 解析失败时也设置模拟数据
          this.currentWeather = {
            type: '晴',
            temperature: '25°C',
            humidity: '50%',
            wind: '南风3级',
            aqi: null
          };
          this.forecast = [
            { date: new Date().toISOString().split('T')[0], type: '晴', high: 25, low: 18, fengxiang: '南风', fengli: '3级' },
            { date: new Date(Date.now() + 86400000).toISOString().split('T')[0], type: '多云', high: 23, low: 17, fengxiang: '北风', fengli: '2级' },
            { date: new Date(Date.now() + 172800000).toISOString().split('T')[0], type: '阴', high: 22, low: 16, fengxiang: '东北风', fengli: '3级' }
          ];
        }
        
        // 提供更具体的错误信息
        if (error.response) {
          // 服务器返回了错误状态码
          this.error = `获取天气数据失败: ${error.response.status} ${error.response.statusText}`;
        } else if (error.request) {
          // 请求发出但没有收到响应
          this.error = '获取天气数据失败: 网络错误，请检查您的网络连接';
        } else {
          this.error = error.message || '获取天气数据失败，请稍后重试';
        }
        
        return null;
      } finally {
        this.loading = false;
      }
    },

    // 清除错误信息
    clearError() {
      this.error = null;
    },

    // 获取天气数据（优先使用缓存）
    getWeatherData() {
      // 如果已经有有效的天气数据，直接返回数据，不发送新请求
      if (this.currentWeather && this.forecast.length > 0) {
        return {
          currentWeather: this.currentWeather,
          forecast: this.forecast,
          location: this.location,
          lastUpdated: this.lastUpdated
        };
      }
      
      // 如果没有有效数据，尝试从localStorage获取
      try {
        const cachedWeather = localStorage.getItem('weatherData');
        if (cachedWeather) {
          const parsedData = JSON.parse(cachedWeather);
          // 更新store状态，确保缓存数据被正确显示
          if (parsedData.currentWeather) {
            this.currentWeather = parsedData.currentWeather;
          }
          if (Array.isArray(parsedData.forecast)) {
            this.forecast = parsedData.forecast;
          }
          if (parsedData.location && typeof parsedData.location === 'object') {
            this.location = parsedData.location;
          }
          if (parsedData.lastUpdated) {
            this.lastUpdated = parsedData.lastUpdated;
          }
          return parsedData;
        }
      } catch (e) {
        console.error('解析缓存的天气数据失败:', e);
      }
      
      // 如果没有任何缓存数据，返回null
      return null;
    },

    // 刷新天气数据
    async refreshWeatherData() {
      // 检查是否需要刷新（10分钟内不重复刷新）
      if (this.lastUpdated && Date.now() - this.lastUpdated.getTime() < 10 * 60 * 1000) {
        return;
      }
      
      await this.fetchWeatherData();
    }
  }
});